import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class HashMapResizeDetector {
    public static void main(String[] args) throws Exception {
        Map<String, Integer> map = new HashMap<>(0); // 初始容量 4，负载因子 0.75（默认）
        
        // 获取 HashMap 的 capacity 字段（反射）
        Field capacityField = HashMap.class.getDeclaredField("table");
        capacityField.setAccessible(true);
        
        int prevCapacity = getCapacity(map, capacityField);
        System.out.println("初始容量: " + prevCapacity);
        // 添加元素，触发扩容（当 size > capacity * loadFactor）
        for (int i = 1; i < 16; i++) {
            map.put("key" + i, i);
            int currentCapacity = getCapacity(map, capacityField);

            if (currentCapacity > prevCapacity) {
                System.out.println("检测到扩容！当前元素数量: " + map.keySet().size() + "旧容量: " + prevCapacity + "，新容量: " + currentCapacity);
                prevCapacity = currentCapacity;
            }
        }
            System.out.println("map = " + map);
    }

    private static int getCapacity(Map<?, ?> map, Field capacityField) throws Exception {
        Object[] table = (Object[]) capacityField.get(map);
        return table == null ? 0 : table.length;
    }
}